package cn.hchaojie.blog.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.hchaojie.blog.domain.AjaxResponse;
import cn.hchaojie.blog.domain.Category;
import cn.hchaojie.blog.service.CategoryService;
import cn.hchaojie.blog.utils.ServiceProxyUtils;

/**
 * 接收请求，解析参数，调用service处理业务逻辑，返回响应
 * @author hchaojie
 *
 */
@WebServlet(
		urlPatterns = {"/category/findAll", "/category/add", "/category/delete", "/category/update"}
)
public class CategoryServlet extends BaseServlet {
	// CategoryService service = new CategoryService();
	CategoryService service = (CategoryService) ServiceProxyUtils.createProxy(new CategoryService());
	
	/*查询所有分类*/
	public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("findAll");

		List<Category> all = service.findAll();
		
		writeListData(resp, all);
	}
	
	public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String categoryName = req.getParameter("name");
		
		Category category = new Category();
		category.setName(categoryName);
		
		service.insert(category);
		
		// 返回一个简单的响应成功消息
		writeSimpleData(resp);
	}
	
	public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.valueOf(req.getParameter("id"));
		
		// 返回一个简单的响应消息
		AjaxResponse response = new AjaxResponse();
		try {
			service.delete(id);
			response.setCode(0);
			response.setMsg("success");
		} catch (Exception e) {
			System.out.println(e);
			
			response.setCode(1);
			response.setMsg("数据库操作失败！");
		}
		
		String string = JSON.toJSONString(response);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(string);
	}
	
	public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.valueOf(req.getParameter("id"));
		String priority = req.getParameter("priority");
		String name = req.getParameter("name");
		
		Category category = new Category();
		category.setId(id);
		category.setName(name);
		if (priority != null) {
			int p = Integer.valueOf(priority);
			category.setPriority(p);
		}
		
		service.update(category);
		
		writeSimpleData(resp);
	}
}
